﻿Imports System.Data.SqlClient

Public Class clsSelectList
    '*// Inherits .... = belangrijke code om van deze klasse zelf een datagridview te maken.
    Inherits ucMyGrid ' Windows.Forms.DataGridView

    Private SelectPanel As New Panel
    Private sBuffer As String
    'Om uw variabele bv frmSelect ook in uw events lijst te krijgen:
    Private WithEvents frmSelect As New Form
    Private WithEvents txtSearch As New TextBox
    Private iMinimumSearchcharacters As Integer
    Private sSQL_Original As String, sSQL_Search As String
    Private sCN_Original As String
    Private sDefaultValue As String
    Private sSelectedValue As String
    Private WithEvents Timer1 As New System.Windows.Forms.Timer
    Private components As System.ComponentModel.IContainer
    Private sTxtSearchDefault As String = "Press 'Home' to enter this search field ..."

    '** Added a boolean to indicate that the entire row has to be returned and not only the first column
    '** and the arraylist which contains the values
    Private bFullRecord As Boolean = False '** boolean set default to false indicating a full record has to be returned
    Private arrSelectedRecord As New ArrayList
    Private ReadOnly Property FeedBackValue___() As String
        Get
            Return sSelectedValue
        End Get
    End Property

    Public WriteOnly Property MinimumSearchcharacters() As Integer
        Set(ByVal value As Integer)
            iMinimumSearchcharacters = value
        End Set
    End Property

    Public WriteOnly Property SQL_Original() As String
        Set(ByVal value As String)
            sSQL_Original = value
        End Set
    End Property

    Public Sub New() 'als we de klasse voor het eerst aanspreken doen we het volgende:
        frmSelect.Controls.Add(SelectPanel)
        frmSelect.Controls.Add(Me)
        frmSelect.Controls.Add(txtSearch)
        '*//Provide message to the user
        txtSearch.Text = sTxtSearchDefault
        txtSearch.ForeColor = Color.Gray
        frmSelect.ShowInTaskbar = False
        frmSelect.MaximizeBox = False
        frmSelect.MinimizeBox = False
        iMinimumSearchcharacters = 0
        sSQL_Original = ""
    End Sub

    Public Function Initialize_Feedback(ByVal connetionString As String, ByVal sSQL As String, ByVal sCurrentValue As String) As String
        '*// De functie die we aanroepen om de geselecteerde waarde terug te geven.
        Try
            '*// Return Current value if nothing would be selected
            If Not IsDBNull(sCurrentValue) Then
                sSelectedValue = sCurrentValue
            End If

            '*// Setup + Populate GRID
            '*// Setuplayout en Setupdatagridview regelen de vormgeving van de datagridview
            SetupLayout()
            SetupDataGridView()

            'Me.ObjSecurity("selectionlist") = frmmdibok.cUser.cSec


            Me.DefaultValue = sCurrentValue
            Me.connection = connetionString
            'If txtSearch.Text <> sTxtSearchDefault And txtSearch.Text.Length >= iMinimumSearchcharacters Then
            Me.SQLstring = sSQL
            'End If

            If sSQL_Original = "" Then sSQL_Original = sSQL
            sCN_Original = connetionString
            If Not IsDBNull(sCurrentValue) Then
                sDefaultValue = sCurrentValue
            End If

            '*// Toon selectielijst (Dialog):

            frmSelect.ShowDialog()

            '*// ... en geef de geselecteerde waarde terug.
            Return sSelectedValue

        Catch ex As Exception
            mdlLOGGING.fLOG("clsSelectList => Initialize_Feedback: " & ex.Message.ToString, 99)
            Return ""
        End Try
    End Function

    '** Added KR -> an extra method that will not only return the first column of the grid bit the entire row in an arraylist.
    Public Function Initialize_Feedback_fullRecord(ByVal connetionString As String, ByVal sSQL As String, ByVal sCurrentValue As String, ByVal sKeyCode As String) As ArrayList
        '*// De functie die we aanroepen om de geselecteerde waarde terug te geven.
        Try

            bFullRecord = True

            '*// Return Current value if nothing would be selected
            If Not IsDBNull(sCurrentValue) Then
                sSelectedValue = sCurrentValue
            End If

            '*// Setup + Populate GRID
            '*// Setuplayout en Setupdatagridview regelen de vormgeving van de datagridview
            SetupLayout()
            SetupDataGridView()

            'Me.ObjSecurity("selectionlist") = frmmdibok.cUser.cSec

            Me.DefaultValue = sCurrentValue
            Me.connection = connetionString

            If sSQL_Original = "" Then sSQL_Original = sSQL
            If sKeyCode <> "" Then
                If Not sSQL.ToLower.Contains("where") Then
                    sSQL &= " WHERE 1 = 0"
                Else
                    sSQL &= " AND 1 = 0"
                End If
            End If

            'If HideCol <> "" Then Me.addColumneToHide(HideCol)

            Me.SQLstring = sSQL

            sCN_Original = connetionString
            If Not IsDBNull(sCurrentValue) Then
                sDefaultValue = sCurrentValue
            End If

            Me.txtSearch.Text = sKeyCode

            '*// Toon selectielijst:
            frmSelect.ShowDialog()
            '*// ... en geef de geselecteerde waarde terug.
            Return arrSelectedRecord

        Catch ex As Exception
            mdlLOGGING.fLOG("clsSelectList => Initialize_Feedback: " & ex.Message.ToString, 99)
            Return New ArrayList
        End Try
    End Function


    Private Sub FeedBack()
        Try
            '** Added: if a fullrecord has to be returned then fill the array instead of the string
            If bFullRecord Then
                If Not Me.CurrentCell Is Nothing Then

                    For i As Integer = 0 To Me.ColumnCount - 3 'The last column = 'edited'

                        Dim tmp As String = Me.Item(i, Me.CurrentCell.RowIndex).Value
                        arrSelectedRecord.Add(tmp)
                    Next
                End If
            Else
                If Not Me.CurrentCell Is Nothing Then
                    sSelectedValue = Me.Item(0, Me.CurrentCell.RowIndex).Value
                End If
            End If



            frmSelect.Close()
        Catch ex As Exception
            mdlLOGGING.fLOG("clsSelectList => Feedback: " & ex.Message.ToString, 99)
        End Try
    End Sub

    Private Sub SetupLayout()
        frmSelect.Size = New Size(300, 500)
        frmSelect.Left = Cursor.Position.X
        frmSelect.Top = Cursor.Position.Y
        SelectPanel.Dock = DockStyle.Top
        SelectPanel.Height = 27
        SelectPanel.Width = 292
        Me.Dock = DockStyle.Fill
        txtSearch.Top = 3
        txtSearch.Left = 9
        txtSearch.Height = 20
        txtSearch.Width = 270
        txtSearch.BringToFront()
        'SelectDatagrid.Focus()
    End Sub
    Private Sub SetupDataGridView()
        With Me.ColumnHeadersDefaultCellStyle
            .BackColor = Color.Navy
            .ForeColor = Color.White
            .Font = New Font(Me.Font, FontStyle.Bold)
        End With
        With Me
            .Name = "SELECT"
            .Location = New Point(8, 8)
            '.Size = New Size(500, 250)
            .AutoSizeRowsMode = _
                DataGridViewAutoSizeRowsMode.AllCells 'DisplayedCellsExceptHeaders
            .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
            .GridColor = Color.Black
            .RowHeadersVisible = False
            .SelectionMode = DataGridViewSelectionMode.FullRowSelect
            .MultiSelect = False
            .Dock = DockStyle.Fill
            .EditMode = DataGridViewEditMode.EditProgrammatically
            .AllowUserToAddRows = False
            .DefaultCellStyle.SelectionBackColor = Color.DodgerBlue
            .ScrollBars = ScrollBars.Both
            .BringToFront()
        End With
    End Sub

    Protected Overrides Sub Finalize()
        Me.Dispose()
        MyBase.Finalize()
    End Sub

    Private Sub txtSearch_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtSearch.GotFocus
        '*// Als je nog niets getypt had om te zoeken, moet je bij het focussen op het zoekveld de boodschap verwijderen.
        '*// Als je al wel iets getypt had, moet je zoekopdracht blijven staan.
        If txtSearch.Text = sTxtSearchDefault Then
            txtSearch.Text = ""
            txtSearch.ForeColor = Color.Black
        End If
    End Sub

    Private Sub txtSearch_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtSearch.KeyDown
        If e.KeyCode = Keys.Down Then
            Me.Focus()
        ElseIf e.KeyCode = Keys.Escape Then
            frmSelect.Close()
        End If
    End Sub

    Private Sub txtSearch_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtSearch.LostFocus
        If txtSearch.Text = "" Then
            txtSearch.Text = sTxtSearchDefault
            txtSearch.ForeColor = Color.Gray
        End If
    End Sub

    Private Sub txtSearch_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtSearch.TextChanged
        Try
            Dim iFirstVisibleRow As Integer = 0
            Dim sSQL As String = "", sWHERE As String = ""
            '*// Elke keer je een letter typt / wijzigt in het zoekvenster, moet de lijst aangepast worden naargelang jouw zoekopdracht.
            If txtSearch.Text <> sTxtSearchDefault And txtSearch.Text.Length >= iMinimumSearchcharacters Then
                Dim j As Integer
                For j = 0 To Me.ColumnCount - 3 '*// -2 Because the last column is = 'edited'
                    If Me.Columns(j).Name = Me.Columns(j).Name.Replace(" ", "") Then
                        If sWHERE <> "" Then
                            sWHERE &= " OR "
                        End If
                        sWHERE &= "([" & Me.Columns(j).Name & "] LIKE '%" & txtSearch.Text.ToString.Replace("'", "''") & "%')"
                    End If
                Next j
                If Me.ColumnCount > 0 Then
                    If sSQL_Original.Contains("WHERE") Then
                        sSQL = sSQL_Original & " AND (" & sWHERE & ")"
                    Else
                        sSQL = sSQL_Original & " WHERE (" & sWHERE & ")"
                    End If
                Else
                    sSQL = sSQL_Original
                End If
                '*// Wanneer je begint te typen, gaat het programma al direct bij de eerste letter alle velden met die letter opzoeken.
                '*// Bij één letter zijn dit er natuurlijk zeer veel. Zelfs als je meerdere letters wil typen gaat het programma eerst 
                '*// naar de eerste letter zoeken en het programma komt even vast te zitten. Daarom gaan we eventjes wachten alvorens 
                '*// te zoeken : een snelle typer heeft dan de tijd om meerdere letters in te tikken alvorens het programma begint te zoeken.
                Timer1.Interval = 300
                Timer1.Enabled = True
                '*// Populate GRID
                sSQL_Search = sSQL
            End If
        Catch ex As Exception
            mdlLOGGING.fLOG("clsSelectList => txtSearch.TextChanged: " & ex.Message.ToString, 99)


        End Try
    End Sub

    Private Sub clsSelectList_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.DoubleClick
        FeedBack()
    End Sub

    Private Sub clsSelectList_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        frmSelect.Cursor = Cursors.WaitCursor

        If e.KeyCode = Keys.Enter Then 'Als je op enter drukt geef je de geselecteerde waarde terug
            FeedBack()
        ElseIf e.KeyCode = Keys.Escape Then 'escape = venster sluiten
            frmSelect.Close()
        ElseIf e.KeyCode = Keys.Home Then 'op home drukken = naar zoekveldje gaan
            Me.txtSearch.Focus()
        ElseIf (e.KeyCode >= Keys.A And e.KeyCode <= Keys.Z) Then ' als je een letter typt dan gaan we op deze letter zoeken, ook zonder
            '                                                       dat je in het zoekveld zit.
            If txtSearch.Text = sTxtSearchDefault Then
                txtSearch.Text = e.KeyData.ToString
                txtSearch.ForeColor = Color.Black
            Else
                txtSearch.Text += e.KeyData.ToString
            End If
        ElseIf (e.KeyCode >= Keys.D0 And e.KeyCode <= Keys.D9) Then
            If txtSearch.Text = sTxtSearchDefault Then
                txtSearch.Text = e.KeyData.ToString.Substring(1)
                txtSearch.ForeColor = Color.Black
            Else
                txtSearch.Text += e.KeyData.ToString.Substring(1)
            End If

        ElseIf e.KeyCode = Keys.Back Then
            If txtSearch.Text.Length >= 1 Then txtSearch.Text = txtSearch.Text.Substring(0, txtSearch.Text.Length - 1)
        End If

        frmSelect.Cursor = Cursors.Default
    End Sub

    Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container
        Me.Timer1 = New System.Windows.Forms.Timer(Me.components)
        CType(Me, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.SuspendLayout()
        CType(Me, System.ComponentModel.ISupportInitialize).EndInit()
        Me.ResumeLayout(False)

    End Sub

    Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        'Als de timer de ingestelde tijd heeft gelopen, gaan we deze functie doen. In dit geval gaan we de timer weer uitzetten.
        Timer1.Enabled = False
        'PopulateDataGridView(sCN_Original, sSQL_Search, sDefaultValue)

        If Me.Visible = True Then
            Me.connection = sCN_Original
            Me.SQLstring = sSQL_Search
        Else
            txtSearch.Text = "Access hasn't been granted"
        End If
    End Sub
End Class
